package com.dingdang.mq;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dingdang.entity.OrderDetails;
import com.dingdang.feign.GoodsFeign;
import com.dingdang.mapper.OrderDetailsMapper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
@RocketMQTransactionListener(txProducerGroup = "trs-group")
public class MQCallBackTransactionListener implements RocketMQLocalTransactionListener
{
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsFeign goodsFeign;

    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object out_trade_no)
    {

        try
        {

            System.out.println("out_trade_no = " + out_trade_no.toString());
            //业务处理
            Long orderId = Long.valueOf(String.valueOf(out_trade_no));
//            OrderDetails orderDetails = orderDetailsMapper.selectById(orderId);
            LambdaQueryWrapper<OrderDetails> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetails::getOrderId,orderId);
            List<OrderDetails> orderDetails = orderDetailsMapper.selectList(wrapper);
            Long carId = Long.parseLong(orderDetails.get(0).getCarId());
            goodsFeign.UpdateaInfo(carId);
//            System.out.println("MQ发送的消息为:" + new String((byte[]) message.getPayload()));
//            System.out.println("操作数据库所需要的参数:" + carId);
//            System.out.println("执行减库存操作---------");
//
//            System.out.println("事务id :" + message.getHeaders().get("TRANSACTION_ID"));
//            System.out.println("消息id :" + message.getHeaders().getId());
        }
        catch (Exception e)
        {
            //处理异常返回ROLLBACK
            redisTemplate.opsForValue().set(message.getHeaders().get("TRANSACTION_ID"), out_trade_no);
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //处理成功返回COMMIT
        // 放入redis中是为了防止本地事务成功之后如果网络波动使得连不上rocketMQ consumer的话  再mq进行回查时给他一个确切的信息 成或否
        redisTemplate.opsForValue().set(message.getHeaders().get("TRANSACTION_ID"), out_trade_no);
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message)
    {
        //通过事务id获取 redis中 对应的本地事务执行状态
        String status = (String) redisTemplate.opsForValue().
                get(message.getHeaders().get("TRANSACTION_ID").toString());
        if ("1".equals(status))
        {
            return RocketMQLocalTransactionState.COMMIT;
        } else if ("2".equals(status))
        {
            //继续处理，或者直接回滚
            //有两种选择
            // 1 继续处理  成功后return COMMIT 消费者就可以正常的消费
            // 2 不处理  直接回滚
            // if 判断一下即可
            return RocketMQLocalTransactionState.ROLLBACK;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

}
